package com.rjpacket.supernews.app;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.rjpacket.supernews.app.databases.DBHelper;
import com.rjpacket.supernews.app.fragments.BlankFragment;
import com.rjpacket.supernews.app.fragments.DiscoverFragment;
import com.rjpacket.supernews.app.fragments.PublishFragment;
import com.rjpacket.supernews.app.models.MyImages;
import com.rjpacket.supernews.app.models.News;
import com.rjpacket.supernews.app.models.NewsDetail;
import com.rjpacket.supernews.app.tasks.DetailTaskCallOnBack;
import com.rjpacket.supernews.app.tasks.RecommendNewsDetailTask;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class NewsDetailActivity extends BaseActivity implements DetailTaskCallOnBack {
    private News news;
    private TextView titleBar;
    private WebView webView;
    private NewsDetail detail;
    private TextView title;
    private TextView source;
    private TextView time;
    private ImageView editButton;
    private ImageView messageButton;
    private ImageView zanButton;
    private ImageView saveButton;
    private ImageView shareButton;

    private View view;
    private DBHelper dbHelper;
    private FragmentManager manager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news_detail);

        Intent intent = getIntent();
        news = (News) intent.getSerializableExtra("news");

        titleBar = (TextView) findViewById(R.id.actionbar_title);

        title = (TextView) findViewById(R.id.detail_title);
        source = (TextView) findViewById(R.id.detail_source);
        time = (TextView) findViewById(R.id.detail_time);

        editButton = (ImageView) findViewById(R.id.detail_edit);
        editButton.setOnClickListener(this);
        messageButton = (ImageView) findViewById(R.id.detail_msg);
        messageButton.setOnClickListener(this);
        zanButton = (ImageView) findViewById(R.id.detail_zan);
        zanButton.setOnClickListener(this);
        saveButton = (ImageView) findViewById(R.id.detail_save);
        saveButton.setOnClickListener(this);
        shareButton = (ImageView) findViewById(R.id.detail_share);
        shareButton.setOnClickListener(this);

        Button buttonView = (Button) findViewById(R.id.btn_activity_news_detail_original);
        buttonView.setOnClickListener(this);

        webView = (WebView) findViewById(R.id.webview_news_detail);

        detail = news.getNewsDetail();

        //TODO 将界面用FramLayout盖住，之后设置隐藏
        manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.detail_container, new DiscoverFragment());
        transaction.commit();

        view = findViewById(R.id.detail_container);

        dbHelper = new DBHelper(this);

        if (detail != null) {
            String original_url = detail.getOriginal_url();
            if (original_url != null) {
                titleBar.setText(original_url);
            }

            title.setText(detail.getNews_title());
            source.setText(detail.getNews_source());
            time.setText(detail.getNews_showTime());

            initScreen(detail);
        } else {

            RecommendNewsDetailTask task = new RecommendNewsDetailTask(this);

            task.execute(news.getNid(), Integer.toString(news.getDb()), "");
        }
    }

    private void initScreen(NewsDetail detailNews) {
        String contents = detailNews.getNews_content();

        List<MyImages> images = detailNews.getImages();

        Pattern p = Pattern.compile("news_content_image");

        Matcher matcher = p.matcher(contents);

        StringBuffer sb = new StringBuffer();

        DisplayMetrics dm = new DisplayMetrics();
        //获取屏幕信息
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int w = dm.widthPixels;
        int h = dm.heightPixels;

        for (MyImages image : images) {
            String imgUrl = "<img src=" + detailNews.getBase_image_url() + image.getUrl_big() + " width=" + image.getWidth() + " height=" + image.getHeight() + ">";

            if (matcher.find()) {
                matcher.appendReplacement(sb, imgUrl);
            }
        }
        matcher.appendTail(sb);

        contents = sb.toString();

        view.setVisibility(View.INVISIBLE);

        webView.setWebViewClient(new WebViewClient());
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.loadDataWithBaseURL("about:blank", contents, "text/html", "utf-8", null);
    }


    @Override
    public void callBack(Object object, String position) {
        if (object != null) {
            JSONObject json = null;
            try {
                json = new JSONObject((String) object);

                SQLiteDatabase database = dbHelper.getWritableDatabase();

                database.beginTransaction();
                try {
                    ContentValues values = new ContentValues();

                    values.put("jsonDetail", (String) object);
                    values.put("nid", news.getNid());

                    database.insert("myDetails", null, values);

                    database.setTransactionSuccessful();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    database.endTransaction();
                }
                database.close();


            } catch (JSONException e) {
                e.printStackTrace();
            }
            NewsDetail detail1 = new NewsDetail();
            detail1.parseJSON(json);
            news.setNewsDetail(detail1);

            String original_url = detail1.getOriginal_url();
            if (original_url != null) {
                titleBar.setText(original_url);
            }

            title.setText(detail1.getNews_title());
            source.setText(detail1.getNews_source());
            time.setText(detail1.getNews_showTime());

            initScreen(detail1);
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.detail_edit:
                //编辑实现
                view.setVisibility(View.VISIBLE);
                FragmentTransaction transaction = manager.beginTransaction();
                transaction.replace(R.id.detail_container, new PublishFragment());
                transaction.commit();
                break;
            case R.id.detail_msg:
                //评论
                Intent intent = new Intent(this, CommentActivity.class);
                startActivity(intent);
                break;
            case R.id.detail_zan:
                //赞

                break;
            case R.id.detail_save:
                //收藏
                String nid1 = news.getNid();

                String json = news.getJson();

                SQLiteDatabase database = dbHelper.getWritableDatabase();

                Cursor cursor = database.query("myFavorite", null, "position=?", new String[]{nid1}, null, null, null);
                if (cursor != null && cursor.moveToFirst()) {
                    String position = cursor.getString(cursor.getColumnIndex("position"));
                    if (nid1.equals(position)) {
                        return;
                    }
                }

                database.beginTransaction();
                try {
                    ContentValues value = new ContentValues();
                    value.put("jsonNews", json);
                    value.put("position", news.getNid());

//                    int update = database.update("myFavorite", value, "position=?", new String[]{news.getNid()});
//                    if(update == -1){
                    database.insert("myFavorite", null, value);
//                    }

                    database.setTransactionSuccessful();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    database.endTransaction();
                }
                database.close();
                break;
            case R.id.detail_share:
                //分享

                break;
            case R.id.btn_activity_news_detail_original:
                String url = titleBar.getText().toString().trim();
                Intent intent1 = new Intent(this, OriginalDetailActivity.class);
                intent1.putExtra("url", url);
                startActivity(intent1);
                break;
        }

        super.onClick(v);
    }
}
